package comment

import (
	"context"
	"github.com/ifnk/micro-blog/internal/pkg/dbcontext"
	"github.com/ifnk/micro-blog/internal/pkg/log"
	"github.com/ifnk/micro-blog/protobuf/comment_pb"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func NewCommentServer(logger *log.Logger, db *dbcontext.GormDB, jinzhuDB *dbcontext.JinZhuDB) CommentServer {
	return CommentServer{
		logger:                      logger,
		db:                          db,
		CommentServiceDefaultServer: comment_pb.CommentServiceDefaultServer{DB: jinzhuDB.DB},
	}
}

type CommentServer struct {
	comment_pb.CommentServiceDefaultServer
	logger *log.Logger
	db     *dbcontext.GormDB
}

func (s *CommentServer) GetListByPostId(ctx context.Context, request *comment_pb.GetListByPostIdRequest) (*comment_pb.GetListByPostIdResponse, error) {
	var users []*comment_pb.CommentORM
	err := s.db.Where("post_id = ?", request.GetPostId()).Find(&users).Error
	var pbs []*comment_pb.Comment
	for _, user := range users {
		pb, err := user.ToPB(ctx)
		if err != nil {
			return nil, err
		}
		pbs = append(pbs, &pb)
	}
	return &comment_pb.GetListByPostIdResponse{Result: pbs}, err
}

// 创建 comment
func (s *CommentServer) Create(ctx context.Context, in *comment_pb.CreateCommentRequest) (*comment_pb.CreateCommentResponse, error) {
	payload := in.GetPayload()
	orm, _ := payload.ToORM(ctx)

	err := s.db.Create(&orm).Error
	if err != nil {
		return nil, status.Errorf(codes.Internal, "创建评论出错: %v", err.Error)
	}
	pb, _ := orm.ToPB(ctx)
	return &comment_pb.CreateCommentResponse{Result: &pb}, nil
}

// 创建 comment 补偿
func (s *CommentServer) CreateCompensate(ctx context.Context, in *comment_pb.CreateCommentRequest) (*comment_pb.CreateCommentResponse, error) {
	err := s.db.Delete(&comment_pb.CommentORM{}, "uuid = ?", in.GetPayload().GetUuid())
	if err != nil {
		return nil, status.Errorf(codes.Internal, "删除评论出错: %v", err)
	}
	return &comment_pb.CreateCommentResponse{}, nil
}
